<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="用户名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="getList"
          />
        </el-form-item>

        <el-form-item label="所在部门">
          <el-cascader
            v-model="officeIdPid"
            :props="officeProps"
            :options="officeList"
            size="medium"
            filterable
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" v-permission="['admin_sysuser_view']" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button type="primary" v-permission="['admin_sysuser_add']" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="userList" highlight-current-row style="width: 100%;">
       <el-table-column label="序号"  type="index" align="center" width="60"/>
      <el-table-column prop="name" align="center" label="姓名" />
      <el-table-column prop="loginName" align="center" label="登录名" />
      <el-table-column prop="office.name" align="center" label="所在部门" />
      <el-table-column prop="no" align="center" label="工号" />
      <el-table-column prop="mobile" align="center" label="手机号" />
      <el-table-column prop="userType" align="center" :formatter="userTypeFormat" label="用户类型" />
      <el-table-column label="更新时间" align="center" prop="updateDate">
        <template slot-scope="scope">
          <span>{{ scope.row.updateDate | dateFormat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-permission="['admin_sysuser_edit']"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-permission="['admin_sysuser_del']"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getList" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="头像" prop="photo">
              <el-upload
                class="avatar-uploader"
                action="/oss/oss/uploadFile?type=avatar"
                :show-file-list="false"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.photo" :src="form.photo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门" prop="pIds">
              <el-cascader
                v-model="form.pIds"
                :props="officeProps"
                :options="officeList"
                size="medium"
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="登录名" prop="loginName">
              <el-input v-model="form.loginName" placeholder="请输入登录名" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工号" prop="no">
              <el-input v-model="form.no" placeholder="请输入工号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择">
                <el-option
                  v-for="item in userTypeDict"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="角色" prop="roleIdList">
              <el-checkbox-group v-model="form.roleIdList">
                <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="启用" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option
                  v-for="item in statusDict"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import Pagination from '@/components/Pagination'
import { handleTree } from '@/utils'
import { getToken } from '@/utils/auth'
import { validUsername } from '@/utils/validate'

export default {
  name: 'User',
  components: { Pagination },
  directives: { permission },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名,不能少于6位!'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value != undefined && value.length < 6 ) {
        callback(new Error('密码不能少于6位!'))
      } else {
        callback()
      }
    }
    return {
      // 弹出层标题
      title: '',
      // 遮罩层
      loading: true,
      // 用户数据
      userList: [],
      roleList: [],
      officeList: [],
      officeIdPid: [],
      officeProps: { checkStrictly: true, value: 'id', label: 'name' },
      // 总数量
      total: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      // 表单参数
      form: {

      },
      // 显示状态数据字典
      userTypeDict: [{
        value: '0',
        name: '部门经理'
      },
      {
        value: '1',
        name: '个人'
      }, {
        value: '2',
        name: 'CEO'
      }],
      // 显示状态数据字典
      statusDict: [{
        value: 0,
        name: '是'
      },
      {
        value: 1,
        name: '否'
      }],
      // 表单校验
      rules: {
        pIds: [
          { type: 'array', required: true, message: '请选择部门', trigger: 'blur' }
        ],
        roleIdList: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
        ],
        name: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '用户类型不能为空', trigger: 'blur' }
        ],
        loginName: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          {trigger: 'blur', validator: validatePassword }
        ],
        mobile: [
            {
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                message: "请输入正确的手机号码",
                trigger: "blur"
            }
        ],
        email: [
          {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
          }
       ],
      }
    }
  },
  created() {
    this.getOfficeAll()
    this.getList()
  },
   computed: {
      //computed里面可以设置头部信息，如增加tooken
    headers () {
      return {
        'Authorization': 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    // 字典翻译
    userTypeFormat(row, column) {
      const obj = this.userTypeDict.find(dict => dict.value == row.userType)
      return obj.name
    },
    /** 获取部门树 */
    getOfficeAll() {
      this.officeList = []
      this.$store.dispatch('sys/dept/getOfficeAll')
        .then((data) => {
          this.officeList = handleTree(data)
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 获取所有角色 */
    getRoleAll() {
      this.roleList = []
      this.$store.dispatch('sys/role/getRoleAll')
        .then((data) => {
          this.roleList = data
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.form.photo = res.data.fileUrl
    },
    beforeAvatarUpload(file) {
      console.log(file.type)
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /** 查询用户列表 */
    getList() {
      this.queryParams.officeId = this.officeIdPid[this.officeIdPid.length - 1]
      this.$store.dispatch('sys/user/getUserList', this.queryParams)
        .then((data) => {
          this.userList = data.records
          this.total = data.total
          this.loading = false
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        loginName: undefined,
        officeId: undefined,
        name: undefined,
        password: undefined,
        no: undefined,
        email: undefined,
        phone: undefined,
        userType: undefined,
        status: 0,
        pIds: [],
        roleIdList: []
      }
      
      this.$nextTick(()=>{
          this.$refs['form'].resetFields();
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getRoleAll()
      this.open = true
      this.title = '添加用户'
    },
    /** 删除按钮操作 */
    delUser(id) {
      this.$store.dispatch('sys/user/delUser', id).then(() => {
        this.getList()
        this.msg('删除成功')
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getRoleAll()
      this.$store.dispatch('sys/user/getUser', row.id)
        .then((data) => {
          this.form = data
          console.log(data)
          this.form.pIds = data.office.parentIds.substring(2, data.office.parentIds.length - 1).split(',')
          this.form.pIds.push(data.officeId)

          this.form.roleIdList = []
          data.roleList.forEach(role => this.form.roleIdList.push(role.id))
          this.open = true
          this.title = '修改用户'
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
         this.form.officeId = this.form.pIds[this.form.pIds.length - 1]
        if (valid) {
          if (this.form.id !== undefined) {
            this.$store.dispatch('sys/user/updateUser', this.form).then(data => {
              this.msg('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.$store.dispatch('sys/user/saveUser', this.form).then(res => {
              this.msg('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delUser(row.id)
      })
    }
  }
}
</script>
